/*
 * User: alesj
 * Date: 2002.1.17
 * Time: 17:03:16
 */

package com.generalynx.common.international;

import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.ResourceBundle;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.i18n.LocaleContextHolder;

public class DelegatingLanguageFactory implements ILanguageFactory, InitializingBean {

    private static final Log logger = LogFactory.getLog(DelegatingLanguageFactory.class);

    private Map languageFactoryMap;
    private ILanguageFactory defaultLanguageFactory;

    public void afterPropertiesSet() throws Exception {
        if (defaultLanguageFactory == null) {
            throw new IllegalArgumentException("Deafult language factory must be set!");
        }
        if (languageFactoryMap == null) {
            languageFactoryMap = new HashMap();
        }
    }

    public Map getLanguageFactoryMap() {
        return languageFactoryMap;
    }

    public void setLanguageFactoryMap(Map languageFactoryMap) {
        this.languageFactoryMap = languageFactoryMap;
    }

    public ILanguageFactory getDefaultLanguageFactory() {
        return defaultLanguageFactory;
    }

    public void setDefaultLanguageFactory(ILanguageFactory defaultLanguageFactory) {
        this.defaultLanguageFactory = defaultLanguageFactory;
    }

    public ResourceBundle getResourceBundle() {
        Locale locale = LocaleContextHolder.getLocale();
        String language = locale.getLanguage();
        if (language != null && language.length() == 0) {
            language = locale.toString();
        }
        ILanguageFactory languageFactory = (ILanguageFactory)languageFactoryMap.get(language);
        if (languageFactory == null) {
            logger.warn("No language factory for language: '" + language + "'");
            languageFactory = defaultLanguageFactory;
        }
        return languageFactory.getResourceBundle();
    }

}
